<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-menu default-active="1" class="el-menu-demo" mode="horizontal">
          <el-menu-item index="1">员工管理</el-menu-item>
        </el-menu>
        <page-tools :show-before="true">
          <span slot="before">共{{total}}条记录</span>
          <template slot="after">
            <el-button size="small" type="success" @click="$router.push('/import?type=employees')">Excel导入</el-button>
            <el-button size="small" type="danger" @click="exportData">Excel导出</el-button>
            <el-button size="small" type="primary" @click="showDialog = true" :disabled="!checkPermission('POINT-USER-ADD')">新增员工</el-button>
          </template>
        </page-tools>
        <el-card v-loading="loading">
          <el-table border :data="list">
            <el-table-column align="center" label="序号" type="index" sortable width="80"></el-table-column>
            <el-table-column align="center" label="姓名" prop="username" sortable></el-table-column>
            <el-table-column align="center" label="头像" width="120">
              <template v-slot="{ row }">
                <img
                  v-imagerror="require('@/assets/common/head.jpg')"
                  :src="row.staffPhoto"
                  alt
                  style="border-radius: 50%; width: 100px; height: 100px; padding: 10px; cursor: pointer;"
                  @click="showQrCode(row.staffPhoto)"
                />
              </template>
            </el-table-column>
            <el-table-column align="center" label="工号" prop="workNumber" sortable></el-table-column>
            <el-table-column align="center" label="聘用形式" prop="formOfEmployment" sortable :formatter="formatEmployment"></el-table-column>
            <el-table-column align="center" label="部门" prop="departmentName" sortable></el-table-column>
            <el-table-column align="center" label="入职时间" sortable>
              <template v-slot="{ row }">{{ row.timeOfEntry | formatDate }}</template>
            </el-table-column>
            <el-table-column align="center" label="账户状态" sortable>
              <template v-slot="{ row }">
                <el-switch :value="row.enableState === 1"></el-switch>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" sortable fixed="right" width="280">
              <template v-slot="{ row }">
                <el-button type="text" size="small" :disabled="!checkPermission('POINT-USER-UPDATE')" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
                <el-button type="text" size="small">转正</el-button>
                <el-button type="text" size="small">调岗</el-button>
                <el-button type="text" size="small">离职</el-button>
                <el-button type="text" size="small" @click="roleHandle(row.id)">角色</el-button>
                <el-button type="text" size="small" :disabled="!checkPermission('point-user-delete')" @click="delEmployees(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row type="flex" justify="center" align="middle" style="height: 60px">
            <el-pagination
              :current-page="query.page"
              :page-size="query.size"
              :total="total"
              layout="total, prev, pager, next"
              @current-change="pageChange"
            />
          </el-row>
        </el-card>
      </el-card>
    </div>
    <!-- 新增员工组件 -->
    <add-employee :show-dialog.sync="showDialog" @addEmployee="getEmployeesList"></add-employee>
    <!-- 二维码弹出层 -->
    <el-dialog title="二维码" :visible.sync="showCode">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas"></canvas>
      </el-row>
    </el-dialog>
    <!-- 角色权限组件 -->
    <assign-role ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId"></assign-role>
  </div>
</template>

<script>
import EmployeeEnum from '@/api/constant/employees'
import QrCode from 'qrcode'
import { getEmployeesList, getEmployeesSimple, delEmployees } from '@/api/employees'
import AddEmployee from './components/add-employee'
import AssignRole from './components/assign-role'
import { formatDate } from '@/filters'
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      showCode: false,
      loading: false,
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      total: 0,
      list: [],
      showDialog: false,
      showRoleDialog: false,
      userId: null
    }
  },
  created() {
    this.getEmployeesList()
  },
  methods: {
    async getEmployeesList() {
      this.loading = true
      const { total, rows } = await getEmployeesList(this.query)
      this.list = rows
      this.total = total
      this.loading = false
      // console.log(this.list)
    },
    pageChange(val) {
      this.query.page = val
      this.getEmployeesList()
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    async delEmployees(id) {
      try {
        await this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await delEmployees(id)
        this.getEmployeesList()
        this.$message.success('删除员工成功')
      } catch (error) {
        console.log(error)
      }
    },
    exportData() {
      // 导出Excel
      // 表头对应关系
      const headers = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeesList({ page: 1, size: this.total })
        const data = this.formatJson(headers, rows)
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          data, // 具体数据 必填
          filename: '员工信息列表', // 非必填
          multiHeader,
          merges
        })
      })
    },
    formatJson(headers, rows) {
      // rows为[{}] 转换为 [[]]
      // 下面返回的是一个二维数组格式 [[],[],[]]
      return rows.map(item => {
        // item 为rows中的每一个{}
        // 下面这个返回 返回的是 item对象{} 转化的 item对象中键对应的值组成的[]
        return Object.keys(headers).map(key => {
          // 根据headers标题的顺序去找到对应的值
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(val => val.id === item[headers[key]])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
          // 返回对象中每个键对应的值 将其组成数组 即 将{}中的键值对 转换为 只有值组成的[] 且顺序跟headers顺序相同
        })
      })
    },
    showQrCode(url) {
      if (url) {
        this.showCode = true
        // 上一次数据更新完毕 页面渲染完毕 之后执行
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化为二维码
          // 若转化成二维码的信息 是一个地址 就会跳转到该地址 如果不是地址就会显示该信息内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    async roleHandle(id) {
      this.userId = id
      await this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
    }
  }
}
</script>

<style scoped>
.el-icon-office-building {
  font-weight: bolder;
  margin-right: 4px;
}
.el-menu--horizontal > .el-menu-item.is-active {
  color: #409eff;
}
.el-menu--horizontal .el-menu-item:not(.is-disabled):focus,
.el-menu--horizontal .el-menu-item:not(.is-disabled):hover {
  color: #409eff;
  cursor: default;
}
</style>
